package com.aratana.ui;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

import com.aratana.util.ImageUtilities;

@SuppressWarnings("serial")
public class ImagePanel extends JPanel {

	private BufferedImage img;
	private BufferedImage imgToPaint;

	private boolean centered = false;
	private boolean filled = false;
	private boolean mirrorEffect = false;

	public ImagePanel(Image img) {
		setImage(img);
	}

	@Override
	protected void paintComponent(Graphics g) {
		if (imgToPaint == null) {
			if (mirrorEffect) {
				imgToPaint = new BufferedImage(img.getWidth(), (int) (img.getHeight() * 1.5d), BufferedImage.TYPE_INT_ARGB);
				Graphics2D g2 = imgToPaint.createGraphics();
				g2.drawImage(img, 0, 0, this);
				g2.drawImage(ImageUtilities.createGradientAlphaImage(img, 200, img.getHeight() / 2), 0, img.getHeight(), this);
			} else {
				imgToPaint = (BufferedImage) img;
			}
		}

		if (filled) {
			g.drawImage(imgToPaint, 0, 0, getWidth(), getHeight(), this);
		} else if (centered) {
			g.drawImage(imgToPaint, (getWidth() - imgToPaint.getWidth()) / 2, (getHeight() - imgToPaint.getHeight()) / 2, this);
		} else {
			g.drawImage(imgToPaint, 0, 0, this);
		}
	}

	public Image getImage() {
		return img;
	}

	public void setImage(Image img) {
		if (img instanceof BufferedImage) {
			this.img = (BufferedImage) img;
		} else {
			this.img = new BufferedImage(img.getWidth(this), img.getHeight(this), BufferedImage.TYPE_INT_ARGB);
			this.img.createGraphics().drawImage(img, 0, 0, this);
		}
		imgToPaint = null;
	}

	public void pack() {
		setPreferredSize(new Dimension(img.getWidth(), mirrorEffect ? (int) (img.getHeight() * 1.5d) : img.getHeight()));
	}

	public void setCentered(boolean centered) {
		this.centered = centered;
	}

	public boolean isCentered() {
		return centered;
	}

	public void setFilled(boolean filled) {
		this.filled = filled;
	}

	public boolean isFilled() {
		return filled;
	}

	public void setMirrorEffect(boolean mirrorEffect) {
		this.mirrorEffect = mirrorEffect;
		imgToPaint = null;
	}

	public boolean isMirrorEffect() {
		return mirrorEffect;
	}
}
